// vuex
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

// 创建vuex的store
const store = new Vuex.Store({
  // 声明存储的变量
  state: {
    count: 5,
    token: '',
    // 商品ID
    productId: '',
    // 面包屑集合
    breadcrumbItems: [],
  },

  // 更改store的状态
  mutations: {
    increment(state) {
      state.count++
    },
    decrement(state) {
      state.count--
    },
    setToken(state, value) {
      localStorage.setItem('authToken', value);
      state.token = value
    },
    getToken(state) {
      state.token = localStorage.getItem('authToken')
    },
    setProductId(state, val) {
      state.productId = val
    },
    setBreadcrumbItems(state, val) {
      state.breadcrumbItems = val
    },
  },

  // 有异步的时候，需要action
  actions: {
    increment(context) {
      context.commit('increment')
    },
    decrement(context) {
      setTimeout(function () {
        context.commit("decrement")
      }, 10)
    }
  },

  // 通过 getter 进行数据获取
  getters: {
    getState(state) {
      return state.count > 0 ? state.count : 0;
    },
    getToken: function (state) {
      return state.token === '' ? localStorage.getItem('authToken') : state.token
    }
  }
});

export default store
